using FBroSharp;
using FBroSharp.Const;
using FBroSharp.DataType;
using FBroSharp.Event;
using FBroSharp.Lib;
using FBroSharp.Value;
using System;
using System.Windows.Forms;

namespace 虾皮shopee电商数据采集
{
    /// <summary>
    /// 浏览器事件处理器 - 处理浏览器生命周期和网络请求
    /// </summary>
    public class BrowserEvent : FBroSharpBrowserEvent
    {
        private Form1 _form;

        public BrowserEvent(Form1 form)
        {
            _form = form;
        }

        public override void OnAfterCreated(IFBroSharpBrowser browser, IFBroSharpDictionaryValue extrainfo)
        {
            _form.UpdateStatus($"浏览器创建完成，ID：{browser.GetIdentifier()}");
        }

        public override void OnTitleChange(IFBroSharpBrowser browser, string title)
        {
            if (_form.InvokeRequired)
            {
                _form.Invoke(new Action(() => OnTitleChange(browser, title)));
                return;
            }
            _form.UpdateTitle(title);
        }

        public override void OnAddressChange(IFBroSharpBrowser browser, IFBroSharpFrame frame, string url)
        {
            if (frame.IsMain())
            {
                if (_form.InvokeRequired)
                {
                    _form.Invoke(new Action(() => OnAddressChange(browser, frame, url)));
                    return;
                }
                _form.UpdateUrl(url);
            }
        }

        public override void OnLoadingStateChange(IFBroSharpBrowser browser, bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (_form.InvokeRequired)
            {
                _form.Invoke(new Action(() => OnLoadingStateChange(browser, isLoading, canGoBack, canGoForward)));
                return;
            }
            _form.UpdateLoadingState(isLoading);
        }

        public override void OnLoadStart(IFBroSharpBrowser browser, IFBroSharpFrame frame, FBroSharpTransitionType transition_type)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"开始加载: {frame.GetURL()}");
            }
        }

        public override void OnLoadEnd(IFBroSharpBrowser browser, IFBroSharpFrame frame, int httpStatusCode)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载完成: {frame.GetURL()} (HTTP {httpStatusCode})");
                if (_form.InvokeRequired)
                {
                    _form.Invoke(new Action(() => _form.OnPageLoadComplete()));
                    return;
                }
                _form.OnPageLoadComplete();
            }
        }

        public override void OnLoadError(IFBroSharpBrowser browser, IFBroSharpFrame frame, int errorCode, string errorText, string failedUrl)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载失败: {errorText} ({errorCode})");
            }
        }

        // 拦截弹窗，在当前窗口打开
        public override bool OnBeforePopup(IFBroSharpBrowser browser, IFBroSharpFrame frame, string target_url, 
            string target_frame_name, FBroSharpWindowOpenDisposition target_disposition, bool user_gesture, 
            FBroSharpPopupfeatures popupFeatures, ref FBroSharpWindowsInfo windowInfo, 
            ref FBroSharpBrowserSetting settings, ref bool no_javascript_access, IFBroSharpUseExtraData user_settings)
        {
            frame.LoadURL(target_url);
            return true; // true = 阻止弹窗，在当前窗口打开
        }

        // ⚠️ 关键方法：拦截HTTP响应
        public override void GetResourceResponseFilter(IFBroSharpBrowser browser, IFBroSharpFrame frame,
            IFBroSharpRequest request, IFBroSharpResponse response, IFBroSharpResponseFilter set_filter)
        {
            string requestUrl = request.GetURL();
            string requestMethod = request.GetMethod();

            // 只拦截包含特定API的GET请求
            if (requestMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) &&
                requestUrl.Contains("https://shopee.tw/api/v4/pdp/get_pc") &&
                requestUrl.Contains("item_id"))
            {
                Console.WriteLine($"[拦截] 匹配到目标API: {requestUrl}");
                Console.WriteLine($"[拦截] 请求方法: {requestMethod}");

                // 创建拦截器
                ResponseFilterEvent callback = new ResponseFilterEvent(_form);
                callback.url = requestUrl;
                set_filter.SetCallback(callback);
            }
        }

        public override void OnBeforeClose(IFBroSharpBrowser browser)
        {
            _form.UpdateStatus("浏览器即将关闭");
        }

        public override bool DoClose(IFBroSharpBrowser browser)
        {
            return false; // false = 允许关闭
        }
    }
}

